<?php


namespace App\Models;


use App\Handlers\OtherHandler;
use App\Http\Resources\BikeFile\BikeFileCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class Bike extends BaseModel {

    use SoftDeletes;

    protected $table = "bikes";
    public $timestamps = false;
    protected $fillable = [
        'serial',
        'brand',
        'model',
        'year',
        'color',
        'material',
        'size',
        'bikes_categories_id',
        'equipment_group',
        'pedals',
        'carriage',
        'cassette',
        'planetary_hub',
        'singspeed',
        'connecting_rods',
        'chainring',
        'chain',
        'shifters',
        'front_switch',
        'rear_switch',
        'switch_rollers',
        'aerobar',
        'steering_wheel',
        'grips',
        'handlebar_winding',
        'steering_column',
        'stem',
        'rigid_fork',
        'shock_absorber_26',
        'shock_absorber_27_5',
        'shock_absorber_29',
        'shock_absorber_700с',
        'spring',
        'rear_shock_absorber',
        'rim_brakes',
        'disc_brake',
        'brake_levers',
        'saddle',
        'seatpost',
        'cushioned_seatpost',
        'telescopic_seatpost',
        'wheels_26',
        'wheels_27',
        'wheels_29',
        'wheels_700C',
        'rims',
        'tires',
        'inner_tire',
        'sleeve',
        'drum_bushing',
        'power_connecting_rods',
        'power_pedals',
    ];
    protected $dates = [ 'deleted_at' ];

    public function fill( array $attributes ) {
        foreach ( $this->fillable as $val ) {
            if ( ! in_array( $val, array_keys( $attributes ) ) ) {
                $attributes[ $val ] = null;
            }
        }

        return parent::fill( $attributes );
    }

    public function makeSave() {
        global $request;

        $this->color = is_array( $this->color ) ? implode( "-", $this->color ) : $this->color;
        $size=Components::find($this->size);
        if($size && $size->type=="size") {
            $this->size=$size->brand_list;
        }
        $this->save();
        $files_ids       = UserFile::saveFiles();
        $remove_elements = $request->input( "remove" );

        if ( $remove_elements ) {
            foreach ( $remove_elements as $del_order ) {
                $bike_image_delete = [
                    "bikes_id" => $this->id,
                    "order"    => (int) $del_order,
                ];
                $deletable_bike    = BikeFile::where( $bike_image_delete )->first();
                if ( $deletable_bike != null ) {
                    UserFile::removeFile( $deletable_bike->files_id );
                    $deletable_bike->delete();
                }
            }
        }
        if ( $files_ids != null ) {
            $minFilesLength = 0;
            $maxFilesLength = 10;
            $files_ids      = array_splice( $files_ids, $minFilesLength, $maxFilesLength );

            foreach ( $files_ids as $key => $file_id ) {
                $bike_file_params = [
                    "bikes_id" => $this->id,
                    "files_id" => $file_id,
                    "cover"    => isset( $request->input( "orders" )[ $key ] ) ? ( (int) $request->input( "orders" )[ $key ] == 0 ? 1 : 0 ) : ( $key == 0 ? 1 : 0 ),
                    "order"    => isset( $request->input( "orders" )[ $key ] ) ? (int) $request->input( "orders" )[ $key ] : $key,
                ];

                $search = [ "bikes_id" => $this->id, "order" => $bike_file_params["order"] ];
                if ( BikeFile::where( $search )->first() == null ) {
                    ( new BikeFile( $bike_file_params ) )->save();
                } else {
                    $bike_file = BikeFile::where( "bikes_id", $this->id )->where( "order", $bike_file_params["order"] )->first();
                    UserFile::removeFile( $bike_file->files_id );
                    BikeFile::updateByValues( $search, $bike_file_params );
                }

            }
        }
        $all_images = BikeFile::where( [ "bikes_id" => $this->id ] )->orderBy( "order" )->get();
        foreach ( $all_images as $key => $image ) {
            $image->order = $key;
            $image->save();
        }
        $full_location    = OtherHandler::getLocation( $request->input( "location" ) );
        $user_bike        = UserBike::where( "bikes_id", $this->id )->withTrashed()->first();
        $user_bike_params = [
            "users_id"  => auth()->user()->id,
            "bikes_id"  => $this->id,
            "status"    => 1,
            "confirmed" => 1,
            "country"   => $full_location["country"] ?? '',
            "city"      => $full_location["city"] ?? '',
            "address"   => $full_location["address"] ?? '',
            "privacy"   => $request->input( "privacy" ) ?? 0,

        ];


        if ( $user_bike == null ) {
            return ( new UserBike( $user_bike_params ) )->makeSave();
        }


        return UserBike::updateByValues( [ "bikes_id" => $this->id ], $user_bike_params );
    }


    public function getBikeFiles() {

        return $this->hasMany( "App\Models\BikeFile", "bikes_id" )->orderBy( "order" );
    }

    public function getBikeCategory() {

        return $this->belongsTo( "App\Models\BikeCategory", "bikes_categories_id", "id" );
    }

    public function getUserBike() {

        return $this->hasOne( "App\Models\UserBike", "bikes_id" );
    }

    public function delete() {

        UserBike::find( "bikes_id", $this->id )->delete();

        return parent::delete();
    }


    public function getUserBikeLike() {

        $userBikeLike = UserBikeLike::where( "bikes_id", "=", $this->id );
        if ( Auth::check() ) {
            $userBikeLike = $userBikeLike->where( "users_id", auth()->user()->id );
        } else {
            $userBikeLike = $userBikeLike->where( "session_id", Session::getId() );
        }

        return $userBikeLike->first();
    }

    public function getBookmark() {
        return Bookmark::where( "bikes_id", $this->id )->where( "users_id", auth()->user()->id )->first();
    }
}
